#include<sys/un.h>
#include<sys/socket.h>
#include<string.h>
#include<assert.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include <stdlib.h>
#include<ctype.h>
#define SV_SOCK_PATH "/tmp/us_xfr"

#define BUF_SIZE 10
#define BACKLOG 5

int main(int argc ,char ** argv)
{
    if(remove(SV_SOCK_PATH) == -1 && errno != ENOENT)
        puts("remove error"),exit(1);
    // 初始化公共文件
    struct sockaddr_un addr,claddr;
    memset(&addr,0,sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path,SV_SOCK_PATH,sizeof(addr.sun_path) - 1);
    // 打开文件描述符
    int sfd = socket(AF_UNIX,SOCK_DGRAM,0);
    assert(sfd != -1);
    //  建立与这个程序的公共文件
    assert(bind(sfd,(struct sockaddr *) & addr,sizeof(struct sockaddr_un)) != -1);
    
    char buf[BUF_SIZE];
    int len = sizeof( struct sockaddr_un);
    while(1){
        int numRead = 0 ;
        // 接受文件，并且 把接收方的发送地址 存储到claddr中
        assert((numRead = recvfrom(sfd,buf,BUF_SIZE,0,(struct sockaddr *)&claddr,&len)) != -1);

        printf("Server received %d bytes from %s\n ",numRead,claddr.sun_path);
        for(int i = 0 ;i <numRead; ++ i)
            buf[i] = toupper(buf[i]);
        // 发送文件到claddr中
        assert(sendto(sfd,buf,numRead,0,(struct sockaddr *)&claddr,len) == numRead);
    }
    return 0;
}